package router

import (
	"log"

	"github.com/gin-gonic/gin"
	"github.com/swaggo/gin-swagger"
	"github.com/swaggo/gin-swagger/swaggerFiles"
	"go-papers/apis/finance"
	"go-papers/gateway/auth"
	"go-papers/gateway/feed"

	common2 "go-papers/gateway/common"
	"go-papers/gateway/homepage"
	member2 "go-papers/gateway/member"
	order2 "go-papers/gateway/order"

	"go-papers/apis/common"
	"go-papers/apis/content"
	"go-papers/apis/feedback"
	log2 "go-papers/apis/log"
	"go-papers/apis/member"
	"go-papers/apis/monitor"
	"go-papers/apis/order"
	"go-papers/apis/organ"
	"go-papers/apis/system"
	"go-papers/apis/system/dict"
	. "go-papers/apis/tools"
	_ "go-papers/docs"
	"go-papers/handler"
	"go-papers/handler/sd"
	"go-papers/middleware"
	_ "go-papers/pkg/jwtauth"
)

func InitRouter() *gin.Engine {
	r := gin.New()
	r.Use(middleware.LoggerToFile())
	r.Use(middleware.CustomError)
	r.Use(middleware.NoCache)
	r.Use(middleware.Options)
	r.Use(middleware.Secure)
	r.Use(middleware.RequestId())

	//监控信息
	r.GET("/", handler.Ping)
	r.GET("/ping", handler.Ping)
	r.Static("/static", "./static")
	r.GET("/proxy.pac", handler.Ping)
	r.GET("/info", handler.Info)
	svcd := r.Group("/sd")
	{
		svcd.GET("/health", sd.HealthCheck)
		svcd.GET("/disk", sd.DiskCheck)
		svcd.GET("/info", sd.Info)
		svcd.GET("/cpu", sd.CPUCheck)
		svcd.GET("/ram", sd.RAMCheck)
		svcd.GET("/os", sd.OSCheck)
	}

	// -------------member 前台-------------------//

	// -----Pay ----//
	r.POST("/api/wechat/order", common2.OrderBack)
	r.POST("/api/wechat/refund", common2.OrderRefund)

	// ----//

	// the jwt middleware
	authGatewayMiddleware, err := middleware.AuthGatewayInit()
	if err != nil {
		log.Fatalln("Gateway JWT Error", err.Error())
	}

	r.POST("/api/auth/login", authGatewayMiddleware.GatewayLoginHandler)
	r.POST("/api/auth/register", auth.RegisterUser)
	r.POST("/api/auth/sms", auth.Sms)
	r.GET("/api/cache", handler.Cache)

	// ---------------API 前台接口入口--------------------------//
	api := r.Group("/api/")
	api.Use(authGatewayMiddleware.MiddlewareGatewayFunc())
	{
		// 登錄用戶信息
		api.GET("/homepage/recommend", homepage.GetRecommendList)
		api.GET("/homepage/search", homepage.GetSearchList)
		api.GET("/homepage/banner", homepage.GetBannerList)
		api.GET("/homepage/courseList", homepage.GetCourseList)
		api.GET("/homepage/courseInfo/:id", homepage.GetCourse)
		api.GET("/homepage/organList", homepage.GetOrganList)
		api.GET("/homepage/organInfo/:id", homepage.GetOrgan)
		api.POST("/homepage/organCourse", homepage.GetOrganCourse)
		api.GET("/homepage/brandAll", homepage.GetBrandAll)
		api.GET("/homepage/special", homepage.GetSpecial)
		api.GET("/homepage/organMsg", homepage.OrganMsg)
		api.POST("/homepage/organMsg", homepage.OrganMsg)
		api.GET("/homepage/specialInfo/:id", homepage.GetSpecialInfo)
		api.GET("/system/items", homepage.GetSystemItems)

		// 會員詳情
		api.GET("/member/info", member2.GetMember)
		api.POST("/member/upload", common2.Fileupload)
		api.GET("/member/bindMom", member2.BindMom)
		api.POST("/member/bindMom", member2.BindMom)
		api.POST("/member/pwd", member2.UpdatePwd)

		//意见反馈列表
		api.GET("/feedback/list", feed.GetFeedBackList)
		api.GET("/feedback/info/:id", feed.GetFeedBack)
		api.POST("/feedback/add", feed.InsertFeedBack)
		//会员地址
		api.POST("/member/positionV2", member2.UpdateMemberPositionV2)
		api.POST("/member/position", member2.UpdateMemberPosition)
		api.GET("/member/position", member2.GetMemberPosition)

		// 會員學生
		api.GET("/member/studentList", member2.GetMemberStudentList)
		api.GET("/member/getStudent", member2.GetMemberStudent)
		api.POST("/member/addStudent", member2.InsertMemberStudent)
		api.POST("/member/updateStudent", member2.UpdateMemberStudent)
		api.GET("/member/defaultStudent", member2.GetDefaultStudent)
		api.POST("/member/defaultStudent", member2.DefaultStudent)
		api.POST("/member/delStudent", member2.DeleteMemberStudent)
		// 會員 收藏
		api.POST("/member/getCollectList", member2.GetMemberCollectList)
		api.POST("/member/addCollect", member2.InsertMemberCollect)
		api.POST("/member/delCollect", member2.DeleteMemberCollect)
		// 會員 對比PK
		api.POST("/member/getContrastList", member2.GetMemberContrastList)
		api.POST("/member/addContrast", member2.InsertMemberContrast)
		api.POST("/member/updateContrast", member2.UpdateMemberContrast)
		api.POST("/member/delContrast", member2.DeleteMemberContrast)
		api.GET("/member/compare", member2.CompareContrast)
		// 管家媽媽 社區達人
		api.GET("/mom/newuser", member2.GetMomMemberList)
		api.GET("/mom/neworgan", member2.GetOrganList)
		api.POST("/mom/register", member2.RegisterMom)
		api.GET("/mom/share/organ", member2.ShareOrgan)   // 机构佣金
		api.GET("/mom/share/course", member2.ShareCourse) // 课程佣金

		// 訂單x
		api.POST("/order/create", order2.InsertOrder)
		api.GET("/order/list", order2.GetOrderList)
		api.GET("/order/info", order2.GetOrder)
		api.POST("/order/pay", order2.PayOrder)
		api.POST("/order/sureCheck", order2.SureCheck)
		api.POST("/order/refundCheck", order2.RefundCheck)

		// 微信
		api.GET("/wechat/accessToken", common2.GetAccessToken)
		api.POST("/wechat/auth", common2.UpdateOpenId)
		api.POST("/wechat/code", common2.UpdateCode)
		api.POST("/wechat/share", common2.ShareUrl)
		api.POST("/wechat/config", common2.GetConfig)
		//api.POST("/wechat/order", common2.OrderBack)
	}

	//-------------backend 后台--------------------//
	// the jwt middleware
	authMiddleware, err := middleware.AuthInit()
	if err != nil {
		log.Fatalln("JWT Error", err.Error())
	}
	// --------BACKEND -------//
	r.POST("/backend/login", authMiddleware.LoginHandler)
	// Refresh time can be longer than token timeout
	r.GET("/backend/refresh_token", authMiddleware.RefreshHandler)
	r.GET("/backend/routes", Dashboard)
	r.GET("/backend/getCaptcha", system.GenerateCaptchaHandler)
	// 技术-系统信息
	apiv1 := r.Group("/system/")
	{
		apiv1.GET("/monitor/server", monitor.ServerInfo)
		apiv1.GET("/db/tables/page", GetDBTableList)
		apiv1.GET("/db/columns/page", GetDBColumnList)
		apiv1.GET("/tables/page", GetSysTableList)
		apiv1.POST("/tables/info", InsertSysTable)
		apiv1.PUT("/tables/info", UpdateSysTable)
		apiv1.DELETE("/tables/info/:tableId", DeleteSysTables)
		apiv1.GET("/tables/info/:tableId", GetSysTables)
		apiv1.GET("/gen/preview/:tableId", Preview)
		apiv1.GET("/menuTreeselect", system.GetMenuTreeSelect)
	}

	// ---------------后台接口入口--------------------------//
	authBackend := r.Group("/backend/")
	authBackend.Use(authMiddleware.MiddlewareFunc()).Use(middleware.AuthCheckRole())
	{

		// ------- 数据导出 --------- //
		authBackend.GET("/down/member", member.DownMemberList)
		authBackend.GET("/down/mom", member.DownMomList)
		authBackend.GET("/down/brand", organ.DownBrandList)
		authBackend.GET("/down/organ", organ.DownOrganList)
		authBackend.GET("/down/teacher", organ.DownTeacherList)
		authBackend.GET("/down/course", organ.DownCourseList)
		authBackend.GET("/down/order", order.DownOrderList)
		authBackend.GET("/down/money", finance.DownMoneyList)
		authBackend.GET("/down/fianceOrganCourse", finance.DownFianceOrganCourse)
		authBackend.GET("/down/fianceOrganOrder", finance.DownFianceOrganOrder)

		authBackend.GET("/system/menuTreeselect", system.GetUserMenuTreeSelect) // 分配角色权限 时 可选权限
		authBackend.GET("/system/items", homepage.GetSystemItems)
		authBackend.GET("/menuTreeselect", system.GetMenuTreeSelectV2)
		//登錄用戶信息
		authBackend.GET("/getinfo", system.GetInfo)
		authBackend.GET("/user/info", system.GetInfo)
		authBackend.POST("/upload", common.Fileupload)

		authBackend.GET("/common/cfg", common.GetCommonCfgList)
		authBackend.POST("/common/cfg", common.UpdateCommonCfgList)
		//结算
		authBackend.POST("/finance/momShare", finance.MomShare)      // 社区达人 佣金结算
		authBackend.POST("/finance/sureShare", finance.SureShare)    // 佣金状态确认
		authBackend.GET("/organ/sharelist", finance.GetShareList)    // 机构佣金明细
		authBackend.POST("/organ/share", organ.UpdateOrganShare)     // 机构佣金明细
		authBackend.GET("/finance/organCourse", finance.OrganCourse) // 机构财务
		authBackend.GET("/finance/organOrder", finance.OrganOrder)   // 机构订单
		authBackend.POST("/finance/organSure", finance.OrganSure)    // 机构订单

		//創建
		authBackend.GET("/sysUserList", system.GetSysUserList)
		authBackend.POST("/sysUser", system.InsertSysUser) // 新增
		authBackend.PUT("/sysUser", system.UpdateSysUser)
		authBackend.GET("/sysUser", system.GetSysUserInit)
		authBackend.GET("/sysUser/organ", system.GetSysUserOrgan)
		authBackend.GET("/sysUser/info/:id", system.GetSysUser)
		authBackend.DELETE("/sysUser/del/:id", system.DeleteSysUser)

		authBackend.GET("/user/profile", system.GetSysUserProfile)
		authBackend.POST("/user/avatar", system.InsetSysUserAvatar)
		authBackend.POST("/user/pwd", system.SysUserUpdatePwd)

		//---专题 /backend/specialcontent/
		authBackend.GET("/specialcontent/list", content.GetSpecialContentList)
		authBackend.POST("/specialcontent", content.UpdateSpecialContent)
		authBackend.PUT("/specialcontent", content.InsertSpecialContent)
		authBackend.DELETE("/specialcontent/del/:specialId", content.DeleteSpecialContent)
		authBackend.GET("/specialcontent/info/:specialId", content.GetSpecialContent)

		// 用户
		authBackend.GET("/member/mom/list", member.GetMemberMomList)
		authBackend.POST("/member/mom", member.UpdateMemberMom)
		authBackend.GET("/member/list", member.GetMemberList)
		authBackend.GET("/member/student", member.GetMemberStudentList)
		authBackend.POST("/member", member.UpdateMember)
		authBackend.PUT("/member", member.InsertMember)
		authBackend.DELETE("/member/del/:memberId", member.DeleteMember)
		authBackend.GET("/member/info/:memberId", member.GetMember)

		//---意见反馈 /api/feedback/
		authBackend.GET("/feedback/list", feedback.GetFeedBackList)
		authBackend.POST("/feedback", feedback.UpdateFeedBack)
		authBackend.PUT("/feedback", feedback.InsertFeedBack)
		authBackend.DELETE("/feedback/:id", feedback.DeleteFeedBack)
		authBackend.GET("/feedback/info/:id", feedback.GetFeedBack)

		//---訂單管理 /api/order/
		authBackend.GET("/order/list", order.GetOrderList)
		authBackend.POST("/order", order.UpdateOrder)
		authBackend.PUT("/order", order.InsertOrder)
		authBackend.DELETE("/order/:id", order.DeleteOrder)
		authBackend.GET("/order/info/:id", order.GetOrder)
		authBackend.POST("/order/close/:id", order.CloseOrder)

		authBackend.POST("/order/refundCheck", order.RefundCheck)
		authBackend.POST("/order/refund", order.Refund)
		authBackend.GET("/order/refundPre", order.RefundPre)

		//---訂單管理 關聯支付 /backend/orderpay/
		authBackend.GET("/orderpay/list", order.GetOrderPayList)
		authBackend.POST("/orderpay", order.UpdateOrderPay)
		authBackend.PUT("/orderpay", order.InsertOrderPay)
		authBackend.DELETE("/orderpay", order.DeleteOrderPay)
		authBackend.GET("/orderpay/info/:id", order.GetOrderPay)

		//---訂單管理 關聯的學生 /backend/orderstudent/
		authBackend.GET("/orderstudent/list", order.GetOrderStudentList)
		authBackend.POST("/orderstudent", order.UpdateOrderStudent)
		authBackend.PUT("/orderstudent", order.InsertOrderStudent)
		authBackend.DELETE("/orderstudent/:id", order.DeleteOrderStudent)
		authBackend.GET("/orderstudent/info/:id", order.GetOrderStudent)

		//---訂單管理 關聯分紅 /backend/ordershare/
		authBackend.GET("/ordershare/list", order.GetOrderShareList)
		authBackend.POST("/ordershare", order.UpdateOrderShare)
		authBackend.PUT("/ordershare", order.InsertOrderShare)
		authBackend.DELETE("/ordershare", order.DeleteOrderShare)
		authBackend.GET("/ordershare/info/:id", order.GetOrderShare)

		//--- 机构  /backend/organ/
		authBackend.GET("/organ/list", organ.GetOrganList)
		authBackend.POST("/organ", organ.UpdateOrgan)
		authBackend.PUT("/organ", organ.InsertOrgan)
		authBackend.POST("/organ/check", organ.CheckOrgan)
		authBackend.DELETE("/organ/:id", organ.DeleteOrgan)
		authBackend.GET("/organ/info/:id", organ.GetOrgan)

		//-- 课程 /backend/course/
		authBackend.GET("/course/list", organ.GetCourseList)
		authBackend.POST("/course", organ.UpdateCourse)
		authBackend.PUT("/course", organ.InsertCourse)
		authBackend.DELETE("/course", organ.DeleteCourse)
		authBackend.GET("/course/info/:id", organ.GetCourse)
		authBackend.GET("/course/verify", organ.UpdateStatusCourse)
		authBackend.POST("/course/check", organ.CheckCourse)

		// 品牌
		authBackend.GET("/organbrand/list", organ.GetOrganBrandList)
		authBackend.POST("/organbrand", organ.UpdateOrganBrand)
		authBackend.PUT("/organbrand", organ.InsertOrganBrand)
		authBackend.DELETE("/organbrand/del/:id", organ.DeleteOrganBrand)
		authBackend.GET("/organbrand/info/:id", organ.GetOrganBrand)
		authBackend.POST("/organbrand/verify", organ.CheckOrganBrand)
		authBackend.POST("/organbrand/check", organ.CheckOrganBrand)

		// 教師
		authBackend.GET("/organteacher/list", organ.GetOrganTeacherList)
		authBackend.POST("/organteacher", organ.UpdateOrganTeacher)
		authBackend.PUT("/organteacher", organ.InsertOrganTeacher)
		authBackend.DELETE("/organteacher/del/:id", organ.DeleteOrganTeacher)
		authBackend.GET("/organteacher/info/:id", organ.GetOrganTeacher)
		authBackend.POST("/organteacher/check", organ.CheckOrganTeacher)

		//操作日誌
		authBackend.GET("/operloglist", log2.GetOperLogList)
		authBackend.GET("/operlog/get/:operId", log2.GetOperLog)
		authBackend.GET("/operlog/del/:id", log2.DeleteOperLog)

		//部门列表
		authBackend.GET("/deptList", system.GetDeptList)
		authBackend.GET("/deptTree", system.GetDeptTree)
		authBackend.GET("/dept/:id", system.GetDept)
		authBackend.POST("/dept", system.InsertDept)
		authBackend.PUT("/dept", system.UpdateDept)
		authBackend.DELETE("/dept/:id", system.DeleteDept)
		//职位
		authBackend.GET("/dict/datalist", dict.GetDictDataList)
		authBackend.GET("/dict/data/:dictCode", dict.GetDictData)
		authBackend.POST("/dict/data", dict.InsertDictData)
		authBackend.PUT("/dict/data/", dict.UpdateDictData)
		authBackend.DELETE("/dict/data/:dictCode", dict.DeleteDictData)

		authBackend.GET("/dict/typelist", dict.GetDictTypeList)
		authBackend.GET("/dict/type/:dictId", dict.GetDictType)
		authBackend.POST("/dict/type", dict.InsertDictType)
		authBackend.PUT("/dict/type", dict.UpdateDictType)

		authBackend.GET("/dict/typeoptionselect", dict.GetDictTypeOptionSelect)
		authBackend.GET("/dict/databytype/:dictType", dict.GetDictDataByDictType)

		//角色类别
		authBackend.GET("/rolelist", system.GetRoleList)
		authBackend.GET("/role/:roleId", system.GetRole)
		authBackend.POST("/role", system.InsertRole)
		authBackend.PUT("/role", system.UpdateRole)
		authBackend.PUT("/roledatascope", system.UpdateRoleDataScope)
		authBackend.DELETE("/role/:roleId", system.DeleteRole)

		//配置 字典
		authBackend.GET("/configList", system.GetConfigList)
		authBackend.GET("/config/:configId", system.GetConfig)
		authBackend.POST("/config", system.InsertConfig)
		authBackend.PUT("/config", system.UpdateConfig)
		authBackend.DELETE("/config/:configId", system.DeleteConfig)

		//
		authBackend.GET("/roleMenuTreeselect/:roleId", system.GetMenuTreeRoleselect)
		authBackend.GET("/roleDeptTreeselect/:roleId", system.GetDeptTreeRoleselect)

		authBackend.GET("/postlist", system.GetPostList)
		authBackend.GET("/post/:id", system.GetPost)
		authBackend.POST("/post", system.InsertPost)
		authBackend.PUT("/post", system.UpdatePost)
		authBackend.DELETE("/post/:id", system.DeletePost)

		authBackend.GET("/menulist", system.GetMenuList)
		authBackend.GET("/menulistV2", system.GetMenuListV2)
		authBackend.GET("/menu/:id", system.GetMenu)
		authBackend.POST("/menu", system.InsertMenu)
		authBackend.PUT("/menu", system.UpdateMenu)
		authBackend.DELETE("/menu/:id", system.DeleteMenu)
		authBackend.GET("/menurole", system.GetMenuRole)
		authBackend.GET("/menuids", system.GetMenuIDS)

		//登录操作日志
		authBackend.GET("/loginloglist", log2.GetLoginLogList)
		authBackend.GET("/loginlog/:id", log2.GetLoginLog)
		authBackend.POST("/loginlog", log2.InsertLoginLog)
		authBackend.PUT("/loginlog", log2.UpdateLoginLog)
		authBackend.DELETE("/loginlog/:id", log2.DeleteLoginLog)

		authBackend.GET("/configKey/:configKey", system.GetConfigByConfigKey)

		authBackend.POST("/logout", handler.LogOut)
	}
	//r.NoRoute(authMiddleware.MiddlewareFunc(), NoFound)
	if gin.Mode() != "prod" {
		r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
	}

	log.Println("路由加载成功！")
	return r
}

func Dashboard(c *gin.Context) {

	var user = make(map[string]interface{})
	user["login_name"] = "admin"
	user["user_id"] = 1
	user["user_name"] = "管理员"
	user["dept_id"] = 1

	var cmenuList = make(map[string]interface{})
	cmenuList["children"] = nil
	cmenuList["parent_id"] = 1
	cmenuList["title"] = "用户管理"
	cmenuList["name"] = "Sysuser"
	cmenuList["icon"] = "user"
	cmenuList["order_num"] = 1
	cmenuList["id"] = 4
	cmenuList["path"] = "sysuser"
	cmenuList["component"] = "sysuser/index"

	var lista = make([]interface{}, 1)
	lista[0] = cmenuList

	var menuList = make(map[string]interface{})
	menuList["children"] = lista
	menuList["parent_id"] = 1
	menuList["name"] = "Upms"
	menuList["title"] = "权限管理"
	menuList["icon"] = "example"
	menuList["order_num"] = 1
	menuList["id"] = 4
	menuList["path"] = "/upms"
	menuList["component"] = "Layout"

	var list = make([]interface{}, 1)
	list[0] = menuList
	var data = make(map[string]interface{})
	data["user"] = user
	data["menuList"] = list

	var r = make(map[string]interface{})
	r["code"] = 200
	r["data"] = data

	c.JSON(200, r)
}
